import 'package:flutter/material.dart';
import 'package:spring_fairy/model/mood_track.dart';
import 'package:spring_fairy/model/mood_track_point.dart';
import 'package:spring_fairy/model/mood_type.dart';
import 'package:spring_fairy/model/store.dart';
import 'package:spring_fairy/pages/record_point_list_page.dart';
import 'package:spring_fairy/widget/mood_widget.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:intl/intl.dart';

class MoodCalendarPage extends StatefulWidget {
  final Map<MoodTrack,List<MoodTrackPoint>> data;

  const MoodCalendarPage({super.key,required this.data});

  @override
  State<MoodCalendarPage> createState() => _MoodCalendarPageState();
}

class _MoodCalendarPageState extends State<MoodCalendarPage> {
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay = DateTime.now();


  List<MoodTrackPoint> get selectedDayRecords {
    if (_selectedDay == null) return [];
    print(widget.data.keys);
    for(MoodTrack track in widget.data.keys) {
      if(isSameDay(track.trackDate, _selectedDay)) {
        print(widget.data[track]);
        return widget.data[track] ?? [];
      }
    }
    return [];
  }

  List<MoodTrackPoint> _getRecordLoader(DateTime time) {
    for(MoodTrack track in widget.data.keys) {
      if(isSameDay(track.trackDate, time)) {
        return widget.data[track] ?? [];
      }
    }
    return [];
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('心情日历')),
      body: RefreshIndicator(
        onRefresh: _onRefresh,
        child: Column(
          children: [
            TableCalendar(
              firstDay: DateTime(2020),
              lastDay: DateTime(2030),
              focusedDay: _focusedDay,
              selectedDayPredicate: (day) => isSameDay(day, _selectedDay),
              calendarFormat: CalendarFormat.month,
              eventLoader: (date) {
                return _getRecordLoader(date);
              },
             calendarBuilders: CalendarBuilders(
               markerBuilder: (context,time,events) {
                 if (events.isNotEmpty) {
                   return Positioned(
                     top: 10,
                     right: 10,
                     child: Container(
                       width: 8,  // 调整大小
                       height: 8,
                       decoration: BoxDecoration(
                         color: Colors.red,  // 修改颜色
                         shape: BoxShape.circle,
                       ),
                     ),
                   );
                 }
                 return null;
               }
             ),
              onDaySelected: (selectedDay, focusedDay) {
                setState(() {
                  _selectedDay = selectedDay;
                  _focusedDay = focusedDay;
                });
              },
            ),
            const Divider(height: 1),
            Expanded(
              child: selectedDayRecords.isEmpty
                  ? const Center(
                child: Text(
                  '这一天没有记录',
                  style: TextStyle(fontSize: 16, color: Colors.grey),
                ),
              )
                  : ListView.builder(
                itemCount: selectedDayRecords.length,
                itemBuilder: (context, index) {
                  final record = selectedDayRecords[index];
                  MoodType mood = Store.moodTypes().firstWhere((e) => e.id == record.moodTypeId);
                  return ListTile(
                    leading: SizedBox(
                      width: 40,
                        height: 40,
                        child: MoodWidget.list.firstWhere((e) => e.name == mood.name!).lottie),
                    title: Text(record.description ?? '',maxLines: 1),
                    subtitle: Text(
                      DateFormat('HH:mm').format(record.moodTime!),
                      style: const TextStyle(color: Colors.grey),
                    ),
                    onTap: () {
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        for(var track in widget.data.keys) {
                          if(isSameDay(track.trackDate, _selectedDay)) {
                            return Scaffold(
                              appBar: AppBar(),
                              body: RecordPointListPage(track: track, points: widget.data[track] ?? []),
                            );
                          }
                        }
                        return Center(child: Text("Error"));
                      }));
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _onRefresh() async {
    await Store.refreshHistory();
    setState(() {});
  }
}
